package com.boot.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boot.entity.Result;
import com.boot.entity.User;
import com.boot.service.ILogService;
import com.boot.service.IUserService;
import com.boot.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.boot.config.WebConfig.OPTIONS;
import static com.boot.interceptor.LimitIpInterceptor.ipInterLimitPrefix;
import static com.boot.interceptor.LimitIpInterceptor.ipInterLimitSet;
import static com.boot.interceptor.LimitUserInterceptor.userInterLimitPrefix;
import static com.boot.interceptor.LimitUserInterceptor.userInterLimitSet;

/**
 * @author bbyh
 * @description 用户身份验证拦截器
 * @since 2024-04-29
 */
@Component
@Slf4j
public class ValidUserInterceptor implements HandlerInterceptor {
    @Resource
    private IUserService userService;
    @Resource
    private ILogService logService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        try {
            if (OPTIONS.equals(request.getMethod())) {
                return true;
            }

            String ip = IpUtil.getIp(request);
            String username = request.getHeader("username");
            String password = request.getHeader("password");
            String uri = request.getRequestURI();

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, username).eq(User::getPassword, password);
            User user = userService.getOne(wrapper);
            if (user == null) {
                stringRedisTemplate.opsForSet().add(ipInterLimitSet, ipInterLimitPrefix + IpUtil.getIp(request));
                stringRedisTemplate.opsForSet().add(userInterLimitSet, userInterLimitPrefix + username);
                logService.saveInterLog(ip, username, uri);
                Result.writeResult(response, "用户身份验证失败，请求不通过");
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            Result.writeResult(response, "用户身份验证服务出错");
            return false;
        }
    }
}
